import { Injectable, NestInterceptor, ExecutionContext, CallHandler, HttpStatus } from "@nestjs/common";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";
import { ResponseUtil } from "../common/utils/response.util";
import { ApiResponse } from "../../types/api-response.interface";

/**
 * 全局响应拦截器
 * 自动将控制器返回的数据包装成统一的响应格式
 */
@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, ApiResponse<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<ApiResponse<T>> {
    return next.handle().pipe(
      map((data) => {
        // 如果返回的数据已经是标准响应格式，直接返回
        if (data && typeof data === "object" && "code" in data && "success" in data) {
          return data as ApiResponse<T>;
        }

        // 获取HTTP响应对象
        const response = context.switchToHttp().getResponse();
        const statusCode = response.statusCode;

        // 根据状态码判断响应类型
        if (statusCode >= HttpStatus.OK && statusCode < HttpStatus.AMBIGUOUS) {
          // 成功响应
          if (statusCode === HttpStatus.NO_CONTENT || data === null || data === undefined) {
            return ResponseUtil.noContent();
          }
          return ResponseUtil.success(data);
        } else if (statusCode >= 400 && statusCode < HttpStatus.INTERNAL_SERVER_ERROR) {
          // 客户端错误
          return ResponseUtil.error("请求错误", statusCode, data);
        } else if (statusCode >= HttpStatus.INTERNAL_SERVER_ERROR) {
          // 服务器错误
          return ResponseUtil.serverError("服务器内部错误");
        }

        // 默认成功响应
        return ResponseUtil.success(data);
      }),
    );
  }
}
